# Copyright (c) 2025, EAM Team and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class EquipmentPurchaseRequest(Document):
    def validate(self):
        """验证数据"""
        if not self.applicant:
            self.applicant = frappe.session.user
        
        if not self.required_date:
            from frappe.utils import add_days
            self.required_date = add_days(frappe.utils.today(), 30)

    def on_submit(self):
        """提交后创建ERPNext采购申请"""
        if self.workflow_state == "已审批":
            self.create_purchase_request()

    def create_purchase_request(self):
        """创建ERPNext采购申请"""
        try:
            # 创建或获取物料
            item_code = self.get_or_create_item()
            
            # 创建采购申请
            pr = frappe.get_doc({
                "doctype": "Purchase Request",
                "transaction_date": frappe.utils.today(),
                "required_date": self.required_date,
                "department": self.department,
                "items": [{
                    "item_code": item_code,
                    "qty": self.quantity,
                    "rate": self.estimated_cost,
                    "amount": self.estimated_cost * self.quantity,
                    "description": f"{self.equipment_name} - {self.justification}"
                }]
            })
            pr.insert()
            pr.submit()
            
            self.purchase_request = pr.name
            self.item_code = item_code
            self.workflow_state = "已采购"
            self.save()
            
            frappe.msgprint(f"已创建采购申请: {pr.name}")
            
        except Exception as e:
            frappe.log_error(f"创建采购申请失败: {str(e)}", "Equipment Purchase Request")
            frappe.throw(f"创建采购申请失败: {str(e)}")

    def get_or_create_item(self):
        """获取或创建物料"""
        # 检查是否已存在同名物料
        existing_item = frappe.get_all("Item", 
                                     filters={"item_name": self.equipment_name},
                                     limit=1)
        
        if existing_item:
            return existing_item[0].name
        
        # 创建新物料
        item = frappe.get_doc({
            "doctype": "Item",
            "item_code": f"EQ-{self.equipment_name[:20]}",
            "item_name": self.equipment_name,
            "item_group": "Equipment",
            "stock_uom": "Nos",
            "is_stock_item": 1,
            "is_purchase_item": 1,
            "is_sales_item": 0,
            "description": f"设备: {self.equipment_name}\n分类: {self.equipment_category}"
        })
        item.insert()
        
        return item.name

    def update_purchase_status(self, purchase_order=None, purchase_receipt=None):
        """更新采购状态"""
        if purchase_order:
            self.purchase_order = purchase_order
            self.workflow_state = "已下单"
        
        if purchase_receipt:
            self.purchase_receipt = purchase_receipt
            self.workflow_state = "已收货"
        
        self.save()